<template>
  <el-dialog v-model="showEditDialog" :title="isAdd ? '新增角色' : '编辑角色'" width="90%" :before-close="cancel">
    <el-form ref="formRef" :model="role" :rules="roleRules" size="small" label-width="80px">
      <el-form-item label="角色名称" prop="name">
        <el-input size="mini" class="custom-input" placeholder="请输入名称" v-model="role.name"/>
      </el-form-item>
      <el-form-item label="角色编号" prop="code">
        <el-input size="mini" class="custom-input" placeholder="请输入编号" v-model="role.code"/>
      </el-form-item>
      <el-form-item label="描述信息">
        <el-input size="mini" class="custom-input" placeholder="请输入描述" v-model="role.remark" rows="5" type="textarea"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="mini" type="text" @click="cancel">取消</el-button>
        <el-button size="mini" type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import {ref, watch} from "vue"
import {success} from "../../../util/tipsUtils";
import {saveRole, updateRole} from "../../../api/role";
export default {
  emits: ["callback"],
  props: {
    item: {
      type: Object,
      default: () => {
        return {name: "", code: "", remark: ""}
      }
    },
    isAdd: {
      type: Boolean,
      default: false
    },
    show: {
      type: Boolean,
      default: false
    },
    callback: {
      type: Function,
      default: () => {}
    }
  },
  setup(props, context) {
    const showEditDialog = ref(props.show)
    const role = ref({name: "", code: "", remark: ""})
    watch(() => props.show, (nv) => {
        showEditDialog.value = nv
    })
    watch(() => props.item, (nv) => {
      role.value = nv
    })
    const roleRules = {
      name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      code: [{ required: true, message: "请输入编号", trigger: "blur" }]
    }
    const formRef = ref(null)
    const resetForm = () => {
      context.emit("callback")
      formRef.value.resetFields()
      role.value = {name: "", remark: "", code: ""}
    }
    const cancel = () => {
      resetForm()
    }
    const submit = () => {
      formRef.value.validate((valid) => {
        if (!valid) {
          return false
        }
        console.log(role.value)
        if (props.isAdd) {
          saveRole(role.value, res => {
            console.log(res)
            resetForm()
            success("添加成功")
          })
        } else{
          updateRole(role.value, res => {
            console.log(res)
            resetForm()
            success("修改成功")
          })
        }
      })
    }
    return {
      showEditDialog,
      role,
      roleRules,
      formRef,
      cancel,
      submit
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .custom-input {
    width: 100%;
  }
  .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
